package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"zhihu/models/cache"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SendSmsLogic) SendSms(in *zhihurpc.SendSmsRequest) (*zhihurpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSmsErr"+in.Mobile).Val()
	if get == "1" {
		return nil, fmt.Errorf("验证码每分钟只能发送一次")
	}

	init := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(init))
	if err != nil {
		return nil, fmt.Errorf("短信验证码生成失败")
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, init, time.Hour*5)

	cache.Rdb.Incr(l.ctx, "sendSmsErr"+in.Mobile)
	cache.Rdb.Expire(l.ctx, "sendSmsErr"+in.Mobile, time.Minute)
	return &zhihurpc.SendSmsResponse{}, nil
}
